import tkinter as tk
import re
import debug
from pop_win import PopWin
from tkinter.filedialog import askdirectory
from tkinter.messagebox import showinfo
from threading import Thread  #add thread support!! 2020-4-6
"""
2020/04/30 20:16  add 居中代码
    主界面：
        3.设置
            3.1  统一设置表头行数
            3.2  是否进入子目录
            3.3  按sheet 合并
            3.4  是否第一保留文件名
        4.显示info
"""

class Main_UI():
    """
        主界面
    """
    def __init__(self): 
        self.root = tk.Tk()
        self.root.title("表格合并工具")
        self.root.resizable(False, False) #阻止用户调整窗口大小
        root = self.root
        btns_txt = ["1合并当前目录下表格","2合并指定目录下表格","3设置","4关于"]
        self.info = ["合并当前程序所在目录下的表格",
                " 先选择表格所在的目录\n 然后进行表格汇总",
                " 可以设置是否跳过标题行 和 结尾行 是否扫描子目录\n 默认是不跳过 不扫描",
                " 关于本软件的一些信息"]
        self.btns = []
        for i in range(len(btns_txt)):
            btn = tk.Button(root, text=btns_txt[i], 
                width=20,height=5, font="kaiti 18 bold",
                command= lambda ind=i:self.popwin(ind))
            btn.grid(row=i//2, column= i % 2)  # 2 rows and 2 columns
            btn.bind("<Enter>", lambda e,ind=i:self.showinfo(e,ind))
            self.btns.append(btn)

        self.msgVar = tk.StringVar()
        msg = tk.Message(root, textvariable=self.msgVar, relief=tk.GROOVE, 
                bg="gray",anchor=tk.W, width=200)
        self.msgVar.set("Welcome")
        msg.grid(row=2, column=0, columnspan=2,sticky=tk.W+tk.E)

        # default settings
        self.settings = {"headers":0, 
                "all_dirs":False, 
                "recrusive":False,
                "copy_by_sht":False,
                "json_tp": """{ "sht_name1": row_num1, "sht_name2": row_num2, "test": 2}""",
                "use_fname": False,
                }
        
    def config_middle(self):
        """
            居中显示
        """
        self.root.update()
        # juzhong
        config_str= self.root.winfo_geometry()
        w,h,x,y = re.split(r"[x+]", config_str)
        newx = (self.root.winfo_screenwidth() - int(w)) /2
        newy = (self.root.winfo_screenheight() - int(h)) /2
        self.root.geometry("%sx%s+%d+%d" %(w,h,newx,newy))



    def showinfo(self, event, ind):
        """ 在说明栏显示信息 """
        self.msgVar.set(self.info[ind])

    def run(self):
        """  运行"""
        debug.init() 
        self.root.mainloop()
    
    def popwin(self, ind):
        """弹出窗口"""
        debug.prt("click btn %d" % ind)
        if ind == 0  or ind == 1: # 合并 0当前目录 1自选目录
            directory = '.' if ind == 0 else askdirectory()
            debug.prt(" you select [%s]" % directory)
            if len(directory) != 0:
                pop = PopWin(self.root, self.settings,"选择合并..", directory)
                task = Thread(target=pop.run)
                task.start()
                #task.join()

        elif ind == 2: #设置功能
            self.show_setting_win()
        elif ind == 3:
            longtxt = """ 
            本软件使用python 编写,
            目标应用: 工作中常常需要合并 excel表格，大部分表格结构相似，
                    所以可以让电脑程序自己来做
            作者：徐鹏
            单位：景德镇市审计局财经科 
            时间：2020-4-4 """
            showinfo("About", longtxt)

        self.root.update()
    
    def setting_change(self, *args):
        s = self.rowvar.get()
        debug.prt("jump over lines {} ".format(s))
        if s.isdecimal():
            self.settings["headers"] = int(s)
            debug.prt(" change the headers >>> %d" % int(s))
    
    def set_recrusive(self):
        """设置是否 扫描子目录"""
        self.settings["recrusive"] = self.ckbtn_var.get()
    
    def set_copy_by_sht(self):
        self.settings["copy_by_sht"]  = self.ckbtn_var2.get()

    def set_use_filename(self):
        self.settings["use_fname"]  = self.ck_filename.get()

    def show_setting_win(self):
        """
            show 设置窗口
        """
            # 设置 
        self.set_win = tk.Toplevel(self.root)
        self.set_win.title("设置")
        win = self.set_win
        win.geometry("300x200")
        #tk.Label(win, text="标题行数：").pack(anchor=tk.W, side=tk.LEFT)
        frm_top = tk.Frame(win)
        tk.Label(frm_top, text="标题行数：").pack(side=tk.LEFT)
        self.rowvar = tk.StringVar()

        entry = tk.Entry(frm_top, width=5, textvariable=self.rowvar)
        #entry.pack(anchor=tk.W, side=tk.LEFT)
        entry.pack(side=tk.LEFT)
        self.rowvar.set(self.settings["headers"])
        self.rowvar.trace("w", self.setting_change)
        frm_top.pack(anchor=tk.W,padx=5,pady=5, ipadx=5, ipady=5)

        self.ckbtn_var = tk.BooleanVar()
        self.ckbtn_var.set(self.settings["recrusive"])
        ckbtn = tk.Checkbutton(win, text="扫描子目录", variable=self.ckbtn_var,
                    command=self.set_recrusive)
        ckbtn.pack(anchor=tk.W, padx=10, pady=5)

        self.ckbtn_var2 = tk.BooleanVar()
        self.ckbtn_var2.set(self.settings["copy_by_sht"])
        ckbtn = tk.Checkbutton(win, text="按sheet拷贝--(需要设置shtName和标题行数)",
                    variable=self.ckbtn_var2, command=self.set_copy_by_sht)
        ckbtn.pack(anchor=tk.W, padx=10, pady=5)

        self.ck_filename = tk.BooleanVar()
        self.ck_filename.set(self.settings["use_fname"])
        ckbtn = tk.Checkbutton(win, text="在第一列保留文件名",
                    variable=self.ck_filename, command=self.set_use_filename)
        ckbtn.pack(anchor=tk.W, padx=10, pady=5)
        pass




if __name__ == "__main__":
    app = Main_UI()
    app.run()
    print("Exit???")
    debug.myquit()